<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;

class PasswordController extends Controller
{
    //修改密码
    public function update(Request $request)
    {
        $userinfo =  request()->user();
        $request->validate([
            'password' => 'required|string|min:6',
            'repassword' => 'required|string|min:6',
        ]);
        if(!Hash::check($request->password,$userinfo->password)){
            return response()->json(['status' => 0,'message' => '原密码错误']);
        }
        $userinfo->update(['password' => bcrypt($request->repassword)]);
        return response()->json(['status' => 1,'message' => '密码修改成功']);
    }

    //忘记密码
    public function repass(Request $request)
    {
         if (!empty(request('code')) && Redis::get($request->mobile) == request('code')) {
            $request->validate([
                'mobile' => 'required|regex:/^1[34578][0-9]{9}$/|exists:users',
                'password' => 'required|string|min:6',
            ]);
            $oldpassword = User::where('mobile',$request->mobile)->value('password');
            if(Hash::check($request->password,$oldpassword)){
                return response()->json(['status' => 0, 'message' => '新密码与愿密码一致']);
            }
            User::where('mobile',$request->mobile)->update(['password' => bcrypt(request('password'))]);
            return response()->json(['status' => 1, 'message' => '密码修改成功']);
        }else{
            return response()->json(['status' => 0, 'message' => '验证码已失效']);
        }
    }

}
